﻿using System;
using System.Collections.Generic;

using Ah.Testudin.Engine.Actors.Components.Animation;
using Ah.Testudin.Engine.Events;
using Ah.Testudin.Engine.Events.Components;

using Microsoft.Xna.Framework;

namespace Ah.Testudin.Engine.Processes
{
    public class AnimationUpdateProcess : ProcessBase
    {
        #region Private Member Variables

        private IList<IAnimationComponent> _animationComponents;

        #endregion

        #region Constructors

        public AnimationUpdateProcess(IEventManager eventManager)
        {
            if (eventManager == null)
            {
                throw new ArgumentNullException("eventManager");
            }

            _animationComponents = new List<IAnimationComponent>();

            eventManager.RegisterEventHandler(
                EventType.AnimationComponentCreated, 
                HandleAnimationComponentCreated);
        }

        #endregion

        #region ProcessBase

        public override void Update(GameTime gameTime)
        {
            IList<IAnimationComponent> animationComponentsToDelete = new List<IAnimationComponent>();

            foreach (IAnimationComponent currentAnimationComponent in _animationComponents)
            {
                if (currentAnimationComponent.Status == AnimationStatus.Running)
                {
                    currentAnimationComponent.Update(gameTime);
                }
                else if (currentAnimationComponent.Status == AnimationStatus.Finished)
                {
                    animationComponentsToDelete.Add(currentAnimationComponent);
                }
            }

            foreach (IAnimationComponent currentAnimationComponentToDelete in animationComponentsToDelete)
            {
                _animationComponents.Remove(currentAnimationComponentToDelete);
            }
        }

        #endregion

        #region Private Methods

        private void HandleAnimationComponentCreated(ITestudinEvent testudinEvent)
        {
            AnimationComponentCreatedEvent animationComponentCreatedEvent = 
                testudinEvent as AnimationComponentCreatedEvent;

            if (animationComponentCreatedEvent == null)
            {
                throw new ArgumentException("Expected AnimationComponentCreatedEvent");
            }

            _animationComponents.Add(animationComponentCreatedEvent.AnimationComponent);
        }

        #endregion
    }
}
